<template>
  <div class="chatArea publicZIndexChatArea">
    <vue-scroll :ops="options" ref="vueScroll">
      <div class="messageItem" v-for="item in renderChatList" :id="item.id" :key="item.id">
        <div class="top publicVCenter">
          <img :src="item.headImg" class="headImg" />
          <div class="nickname">{{ item.userName }}</div>
          <div class="sexType" :class="{ boy: item.miaoSex === '1', girl: item.miaoSex === '2' }"></div>
          <div class="status publicHvCenter" v-show="item.currentStatus">{{ item.currentStatus }}</div>
          <div class="deskNum publicHvCenter" v-show="item.deskNum">{{ item.deskNum }}桌</div>
        </div>
        <div class="content" :class="{ hasGift: item.giftImg }">
          <label v-if="item.giftImg">送来了</label>{{ item.content }}
          <img :src="item.giftImg" v-if="item.giftImg" class="giftImg" />
        </div>
        <div class="time" v-if="item.displayTime">{{ item.displayTime }}</div>
        <img :src="item.photoUrl" class="photo" v-if="item.photoUrl" />
      </div>
    </vue-scroll>
  </div>
</template>

<script>
import { getChatMessage } from '@/api/chat/index';
import { mapState, mapMutations } from 'vuex';
import { generateRandomId } from '@/utils/index';

let isFirstScroll = false;
export default {
  name: 'chatArea',
  data() {
    return {
      options: {
        bar: {
          opacity: 0,
        },
      },
    };
  },
  computed: {
    ...mapState({
      giftList01: (state) => state.live.giftList01,
      giftList02: (state) => state.live.giftList02,
      giftList03: (state) => state.live.giftList03,
      chatList: (state) => state.live.chatList,
      chatAreaScrollId: (state) => state.app.chatAreaScrollId,
      liveId: (state) => state.live.liveId,
    }),
    renderChatList() {
      return this.chatList.map((item) => {
        const sendTime = this.extractChatTime(item);
        return {
          ...item,
          displayTime: this.formatChatTime(sendTime),
        };
      });
    },
  },
  watch: {
    chatAreaScrollId(newVal) {
      this.$nextTick(() => {
        if (!isFirstScroll) {
          isFirstScroll = true;
          this.$refs.vueScroll.scrollTo({ y: '200%' }, 1000);
        } else {
          this.$refs.vueScroll.scrollIntoView(`#${newVal}`, 1000);
        }
      });
    },
    giftList01(newVal) {
      if (newVal.length > 0) {
        this.getChatMessage();
      }
    },
  },
  created() {
    this.isFirstScroll = false;
  },
  mounted() {},
  methods: {
    ...mapMutations({
      initChatList: 'live/initChatList',
      setChatAreaScrollId: 'app/setChatAreaScrollId',
    }),
    // 获取聊天记录
    getChatMessage() {
      getChatMessage()
        .then((res) => {
          console.log('***聊天记录2***', res);
          if (res && res.chat_list && res.chat_list.length > 0) {
            res.chat_list.reverse();
            const list = res.chat_list.map((item) => {
              // 不包含文字的礼物处理
              if (
                item.miaoLiwuId
                && item.miaoLiwuId.indexOf('Picture_Screen_LG') === -1
                && item.miaoLiwuId.indexOf('Domineering_LG') === -1
                && item.miaoLiwuId.indexOf('Domineering_Screen') === -1
              ) {
                const allGiftList = this.giftList01.concat(this.giftList02).concat(this.giftList03);
                const tmpGift = allGiftList.find((i) => i.giftconst === item.miaoLiwuId || i.giftconst.indexOf(item.miaoLiwuId) > -1);
                if (tmpGift) {
                  item.miaoContent = `${tmpGift.giftname}`;
                  item.giftImg = tmpGift.imglink;
                }
              }
              return {
                id: generateRandomId(),
                userName: item.miaoName.length > 4 ? `${item.miaoName.slice(0, 4)}...` : item.miaoName,
                content: item.miaoContent,
                headImg: item.miaoTxUrl,
                photoUrl: item.miaoTpUrl,
                giftImg: item.giftImg,
                miaoVip: this.liveId === item.miaoVipSplid ? item.miaoVip : '',
                vipLevel: item.miaoVipLevel,
                miaoSex: item.miaoSex,
                currentStatus: item.miaoPosition,
                deskNum: item.miaoTableNumber,
                sendTime: this.extractChatTime(item),
              };
            });
            // 聊天记录存入缓存
            this.initChatList(list);
            // 聊天框区域滚动到指定位置
            this.setChatAreaScrollId(list[list.length - 1].id);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    extractChatTime(item) {
      if (!item || typeof item !== 'object') {
        return '';
      }
      const keys = [
        'sendTime',
        'send_time',
        'msgTime',
        'msg_time',
        'createTime',
        'create_time',
        'addTime',
        'add_time',
        'miaoTime',
        'miao_time',
        'ctime',
        'time',
      ];
      for (let i = 0; i < keys.length; i += 1) {
        const key = keys[i];
        if (item[key]) {
          return item[key];
        }
      }
      return '';
    },
    formatChatTime(time) {
      if (time === undefined || time === null || time === '') {
        return '';
      }
      let dateObj = null;
      if (typeof time === 'number') {
        const normalized = time < 1e12 ? time * 1000 : time;
        dateObj = new Date(normalized);
      } else if (typeof time === 'string') {
        const trimmed = time.trim();
        if (!trimmed) {
          return '';
        }
        if (/^\d+$/.test(trimmed)) {
          const num = trimmed.length === 10 ? Number(trimmed) * 1000 : Number(trimmed);
          dateObj = new Date(num);
        } else {
          const normalized = trimmed.replace(/-/g, '/');
          dateObj = new Date(normalized);
          if (Number.isNaN(dateObj.getTime())) {
            dateObj = new Date(trimmed);
          }
        }
      }
      if (!(dateObj instanceof Date) || Number.isNaN(dateObj.getTime())) {
        return typeof time === 'string' ? time : '';
      }
      const pad = (val) => `${val}`.padStart(2, '0');
      const now = new Date();
      const isSameDay = now.getFullYear() === dateObj.getFullYear()
        && now.getMonth() === dateObj.getMonth()
        && now.getDate() === dateObj.getDate();
      const hhmmss = `${pad(dateObj.getHours())}:${pad(dateObj.getMinutes())}:${pad(dateObj.getSeconds())}`;
      if (isSameDay) {
        return hhmmss;
      }
      const y = dateObj.getFullYear();
      const m = pad(dateObj.getMonth() + 1);
      const d = pad(dateObj.getDate());
      return `${y}-${m}-${d} ${hhmmss}`;
    },
  },
};
</script>

<style lang="less" scoped>
.chatArea {
  position: absolute;
  width: 520px;
  height: 780px;
  bottom: 330px;
  color: #fff;
  padding-left: 30px;
  .messageItem {
    background-color: rgba(0, 0, 0, 0.2);
    border-radius: 0px 16px 16px 16px;
    color: #ffffff;
    padding: 20px 18px;
    position: relative;
    width: 490px;
    margin: 32px 0;
    .top {
      .headImg {
        width: 48px;
        height: 48px;
        border-radius: 50%;
      }
      .nickname {
        font-size: 24px;
        font-weight: 400;
        color: #ffffff;
        margin-left: 16px;
      }
      .sexType {
        width: 40px;
        height: 28px;
        background-size: 100% 100%;
        margin-left: 16px;
        &.boy {
          background-image: url('../../../assets/image/hdBar/manIcon.png');
        }
        &.girl {
          background-image: url('../../../assets/image/hdBar/womanIcon.png');
        }
      }
      .status {
        color: #F8E18D;
        font-size: 28px;
        font-weight: 400;
        margin-left: 16px;
      }
      .deskNum {
        background: #f34c91;
        position: absolute;
        font-size: 20px;
        font-weight: 400;
        color: #ffffff;
        top: -18px;
        right: 0px;
        border-radius: 50%;
        width: 44px;
        height: 44px;
      }
    }
    .content {
      font-size: 28px;
      margin-top: 14px;
      display: flex;
      label {
        color: #fa3fc3;
        margin-right: 12px;
      }
      .giftImg {
        height: 122px;
        margin-left: 50px;
      }
      &.hasGift {
        margin-top: 42px;
        .giftImg {
          margin-top: -24px;
        }
      }
    }
    .photo {
      width: 456px;
      height: auto;
    }
    .time {
      font-size: 20px;
      color: rgba(255, 255, 255, 0.6);
      margin-top: 12px;
    }
  }
}
</style>
